
<div class="auth-form mt-3 mx-auto">
    <h2 class="p-4 fw-bold fs-24 text-center">登录</h2>
    <form id="auth-form" method="POST" autocomplete="off">
        <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
        <div class="form-floating mb-4">
            <input type="text" class="form-control rounded-0" name="username" id="username" placeholder="用户名" autocomplete="off" required autofocus>
            <label for="username" id="nameHelp">用户名</label>
        </div>
        <div class="form-floating mb-4">
            <input type="password" class="form-control" name="password" id="password" placeholder="密码" required disabled>
            <label for="password" id="passwordHelp">密码</label>
        </div>
        <div class="form-floating mb-4">
            <input type="text" class="form-control" name="captcha" id="captcha" placeholder="验证码" required>
            <img src="/user/captcha" id="resetCaptcha" class="auth-captcha hand" data-bs-toggle="tooltip" data-bs-title="点击刷新验证码">
            <label for="captcha" id="captchaHelp">验证码</label>
        </div>
        <button type="button" id="submitButton" class="btn btn-secondary w-100 auth-btn px-0">登录</button>
        <!-- <button type="submit" class="btn btn-secondary w-100 auth-btn px-0">登录</button> -->
    </form>
    <p class="text-center mt-4">
        <a href="/user/register" class="btn btn-light">没有账号？点此注册</a>
    </p>
    <hr class="hr-solid-content" data-content="社交账号登录">
</div>


<script>
document.addEventListener("DOMContentLoaded", function() {
    const inputValidations = { name: false, password: false, captcha: false };
    const helpTexts = {
        name: document.getElementById('nameHelp'),
        password: document.getElementById('passwordHelp'),
        captcha: document.getElementById('captchaHelp')
    };
    const inputs = {
        name: document.getElementById('username'),
        password: document.getElementById('password'),
        captcha: document.getElementById('captcha')
    };
    const form = document.getElementById('auth-form');
    const captchaImg = document.querySelector(".auth-captcha");
    const submitButton = document.getElementById('submitButton');
    const minLengths = { name: 3, password: 6, captcha: 4 };


    function validateInput(type) {
        const input = inputs[type];
        const help = helpTexts[type];
        const minLength = minLengths[type];
        const value = input.value.trim();
        const placeholder = input.placeholder;

        if (value.length < minLength) {
            input.classList.add('is-invalid');
            help.textContent = `请输入至少 ${minLength} 位数`;
            inputValidations[type] = false;
        } else {
            help.textContent = placeholder;
            input.classList.remove('is-invalid');
            inputValidations[type] = true;
        }
    }

    ['name', 'password', 'captcha'].forEach(type => {
        inputs[type].addEventListener('change', function() {
            validateInput(type);
        });
    });

    submitButton.addEventListener('click', async function(event) {
        event.preventDefault();
        if (!inputValidations.name || !inputValidations.password || !inputValidations.captcha) return;

        try {
            const response = await fetch('/user/login/submit', {
                method: 'POST',
                body: new FormData(form)
            });
            const res = await response.json();
            if (res.status === 'success') {
                toast.success(res.message);
                setTimeout(() => {
                    document.referrer === "" ? (window.location.href = "/") : window.history.back();
                }, 2000);
            } else {
                toast.error(res.message);
                captchaImg.setAttribute("src", "/user/captcha/" + Math.random());
            }
        } catch (error) {
            console.error(error); // 处理错误，避免被忽略。
        }
    });
});
</script>
